package com.koala.auth.service;


import cn.hutool.core.util.ArrayUtil;
import com.koala.common.security.service.KoalaUser;
import com.koala.auth.feign.UserService;
import com.koala.common.core.utils.RT;
import com.koala.upms.api.entity.SysUser;
import com.koala.upms.api.vo.UserInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

	private final UserService userService;



	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		RT<UserInfo> result = userService.findUserByUsername(username);
		return getUserDetails(result);
	}

	private UserDetails getUserDetails(RT<UserInfo> result) {
		if (result== null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		UserInfo info = result.getData();
		Set<String> authSet = new HashSet<String>();
			if (ArrayUtil.isNotEmpty(info.getRoles())) {
			Arrays.asList(info.getRoles()).forEach(role -> authSet.add("ROLE_" +role));
			authSet.addAll(Arrays.asList(info.getPermissions()));
		}
		Collection<? extends GrantedAuthority> authorityList = AuthorityUtils
				.createAuthorityList(authSet.toArray(new String[0]));
		SysUser user = info.getUser();
		return new KoalaUser(user.getUserId(),user.getDeptId(),user.getUsername(), "{bcrypt}"+info.getUser().getPassword(),
				true,true,true,true,authorityList);
	}

}
